package com.pubinfo.passbook.common.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.pubinfo.passbook.common.entity.TRabbitmqPerson;
import com.pubinfo.passbook.common.exception.ServiceException;
import com.pubinfo.passbook.common.mapper.TRabbitmqOrgConvertMapper;
import com.pubinfo.passbook.common.mapper.TRabbitmqPersonMapper;
import com.pubinfo.passbook.common.mapper.TSystemRoleMapper;
import com.pubinfo.passbook.common.model.bo.Excel;
import com.pubinfo.passbook.common.model.ruler.CompanyExcel;
import com.pubinfo.passbook.common.service.master.TSubsidiaryInfoService;
import com.pubinfo.passbook.common.service.master.TSubsidiaryPrivateKeyService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CompanyExcelDataListener extends AnalysisEventListener<CompanyExcel>
{
    /**
     * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 1000;
    List<CompanyExcel> list = new ArrayList();

    private TRabbitmqPersonMapper tRabbitmqPersonMapper;

    private TSystemRoleMapper tSystemRoleMapper;

    private TRabbitmqOrgConvertMapper tRabbitmqOrgConvertMapper;

    public List<CompanyExcel> getList() {
        return list;
    }

    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private TSubsidiaryPrivateKeyService keyService;
    private TSubsidiaryInfoService infoService;

    public CompanyExcelDataListener(TRabbitmqPersonMapper tRabbitmqPersonMapper,TSystemRoleMapper tSystemRoleMapper,TRabbitmqOrgConvertMapper tRabbitmqOrgConvertMapper)
    {
        this.tSystemRoleMapper=tSystemRoleMapper;
        this.tRabbitmqPersonMapper=tRabbitmqPersonMapper;
        this.tRabbitmqOrgConvertMapper=tRabbitmqOrgConvertMapper;
    }

    public CompanyExcelDataListener() {
        // 这里是demo，所以随便new一个。实际使用如果到了spring,请使用下面的有参构造函数
        //    uploadDAO = new TAutoInterfaceService();
    }


    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. Is is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(CompanyExcel data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    private Boolean checkObjIsNull(Excel interfaceImport) {
        for (Field f : interfaceImport.getClass().getDeclaredFields()) {
            f.setAccessible(true);
            try {
                if (f.get(interfaceImport) == null || "".equals(f.get(interfaceImport).toString())) { //判断字段是否为空，并且对象属性中的基本都会转为对象类型来判断
                    //  throw new ServiceException("请求参数不能为空");
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
        return true;
    }

    /**
     * 加上存储数据库
     */
    public void saveData() {

        for (CompanyExcel companyExcel : list) {
            List<TRabbitmqPerson> tRabbitmqPeople= tRabbitmqPersonMapper.selectAcctByNameAndPhone(companyExcel.getAcctName(),null);
            if(tRabbitmqPeople.size()>1)
            {
                tRabbitmqPeople= tRabbitmqPersonMapper.selectAcctByNameAndPhone(companyExcel.getAcctName(),companyExcel.getPhone());
                if(tRabbitmqPeople.size()>1)
                {
                    throw new ServiceException("电话号码为"+companyExcel.getPhone()+"的"+companyExcel.getAcctName()+"用户获取失败");
                }
            }

//            if(tRabbitmqPeople.size()!=1)
//            {
//                continue;
//            }
    
            Integer roleId = tSystemRoleMapper.getRoleIdByRoleName(companyExcel.getRoleName());
    
            Integer orgId = tRabbitmqOrgConvertMapper.getOrgIdByOrgName(companyExcel.getOrgName());


            if (!CollectionUtils.isEmpty(tRabbitmqPeople)) {
                tSystemRoleMapper.addUserRoleAndOrgId(tRabbitmqPeople.get(0).getAcct(), tRabbitmqPeople.get(0).getAcctId(), roleId, orgId);
            }
    
        }
    }
}
